<!--
 * @Descripttion: 人员选择主入口
 * @version: V1.0.0
 * @Author: Shuangshuang Song
 * @LastEditors: Shuangshuang Song
 * @Date: 2020-05-23 13:06:45
 * @LastEditTime: 2021-01-22 15:18:56
-->
<template>
  <el-dialog
    id="person-selector-dialog"
    v-if="params.show"
    :visible.sync="params.show"
    :width="params.width || '1000px'"
    :title="params.title || $t('title')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :modal="false"
    :fullscreen="isFullscreen"
    @open="openDialog"
    @close="closeDialog"
    top="100px"
    append-to-body
    custom-class="pro-vue-person-selector"
  >
    <i
      :class="isFullscreen ? 'jeicon-minus' : 'jeicon-max'"
      @click="fullClick()"
      class="jeicon fullScreen-icon"
    />
    <!-- 弹窗遮罩 -->
    <div
      v-if="params.show"
      class="createMask"
    />
    <el-container>
      <el-aside width="400px">
        <el-tabs
          v-model="activeName"
          :class="{'tab-group-cont': activeName == 'group'}"
          @tab-click="handleClick"
          type="border-card"
          stretch
          class="person-dialog-tabs"
        >
          <el-tab-pane
            v-for="(item, index) in tabs"
            :key="index"
            :label="item.label"
            :name="item.name"
            lazy
          >
            <Tree
              :ref="'treeCmp_' + item.name"
              :type="item.name"
              :options="params"
              :isClear="isClear"
              :allSelectList="allSelectList"
              @doSelected="doSelected"
              @toggle2dept="toggle2dept"
            />
          </el-tab-pane>
        </el-tabs>
        <el-button
          v-if="activeName == 'group'"
          @click="createGroup"
          class="add-btn"
          type="text"
          size="small"
          icon="el-icon-plus"
        >
          {{ $t('creategroup') }}
        </el-button>
      </el-aside>
      <el-main>
        <SelectedPerson
          :selections="allSelectList"
          :cloneSelections="allSelectList"
          :params="params"
          :treeDataLength="treeDataLength"
          @clearAll="clearAll"
          @removePerson="removePerson"
          @toGroup="inputGroupName"
        />
      </el-main>
    </el-container>
    <span slot="footer">
      <el-radio-group
        v-model="activeRadio"
        v-if="params.enableFilter"
      >
        <el-radio
          v-for="(item, index) in radios"
          :key="index"
          :label="item.label"
          size="small"
          border
        >{{ item.name }}</el-radio>
      </el-radio-group>
      <span :style="{'float': params.enableFilter ? 'right' : ''}">
        <el-button
          @click="doSure"
          size="small"
          type="primary"
        >{{ params.submitText || $t('confirm') }}</el-button>
        <el-button
          @click="params.show = false"
          size="small"
        >{{ params.cancelText || $t('cancel') }}</el-button>
      </span>
    </span>
  </el-dialog>
</template>

<script>
import VueI18n from 'vue-i18n';
import zh_CN from './lang/zh';
import en from './lang/en';
import getMaxZindex from '../../modules/microMail/util/getZindex';

import Tree from './components/leftTree';
import SelectedPerson from './components/selectedPerson';
import { setCommonGroup } from './actions/actions';

const i18n = new VueI18n({
  locale: JE.getCookies('je-local-lang') || 'zh_CN', // 语言标识
  messages: {
    zh_CN, // 中文语言包
    en, // 英文语言包
  },
});

export default {
  name: 'PersonSelector',
  components: {
    Tree, SelectedPerson,
  },
  i18n,
  props: {
    // 配置参数
    params: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      lang: this.$i18n.locale, // 国际化
      isFullscreen: false, // 是否全屏
      activeName: 'common', // 选中的tab
      tabs: [
        { label: this.$t('common'), name: 'common' },
        { label: this.$t('dept'), name: 'dept' },
        { label: this.$t('role'), name: 'role' },
        { label: this.$t('post'), name: 'post' },
        { label: this.$t('group'), name: 'group' },
      ],
      allSelectList: [], // 所有tab选中的数据
      treeDataLength: 0, // tree节点的长度 用于工作组新建的判断
      isClear: false, // 是否清空
      groupMemberIds: [], // 待创建工作组的成员ID集合
      radios: [
        { label: 'all', name: this.$t('allPerson') },
        { label: 'on', name: this.$t('onPerson') },
        { label: 'off', name: this.$t('offPerson') },
      ],
      activeRadio: 'on',
      needReload: false, // 需要重新请求树形数据的标识字段
      shownTab: [],
    };
  },
  watch: {
    'params.show': function (nv) {
      // 打开弹窗 初始化
      if (!nv) {
        window.removeEventListener('resize', () => {
          this.initHeight();
        });
      }
    },
    // 切换 在职离职radio
    activeRadio(nv) {
      switch (nv) {
        case 'all':
          this.params.params_whereSql = this.params.whereSql || '';
          this.params.params_jquery = this.params.j_query || {};
          this.params.status = '';
          break;
        case 'on':
          const sql = " and (NODETYPE = 'GENERAL' or (NODETYPE = 'LEAF' AND STATUS = '1' ))";
          this.params.params_whereSql = JE.isEmpty(this.params.whereSql) ? sql : this.params.whereSql + sql;
          let j_query = Ext.clone(this.params.j_query || {});
          const conditions = [
            {
              type: 'and',
              value: [
                { type: '=', code: 'NODETYPE', value: 'GENERAL' },
                {
                  type: 'or',
                  value: [
                    { type: '=', code: 'STATUS', value: '1' },
                    { type: '=', code: 'NODETYPE', value: 'LEAF' },
                  ],
                },
              ],
            },
          ];
          if (JE.isNotEmpty(j_query)) {
            j_query = j_query.concat(conditions);
          } else {
            j_query = conditions;
          }
          this.params.params_jquery = j_query;
          this.params.status = '1';
          break;
        case 'off':
          const offsql = " and (NODETYPE = 'GENERAL' or (NODETYPE = 'LEAF' AND STATUS = '1' ))";
          this.params.params_whereSql = JE.isEmpty(this.params.whereSql) ? offsql : this.params.whereSql + offsql;
          let j_query_off = Ext.clone(this.params.j_query || {});
          const offconditions = [
            {
              type: 'and',
              value: [
                { type: '=', code: 'NODETYPE', value: 'GENERAL' },
                {
                  type: 'or',
                  value: [
                    { type: '=', code: 'STATUS', value: '0' },
                    { type: '=', code: 'NODETYPE', value: 'LEAF' },
                  ],
                },
              ],
            },
          ];
          if (JE.isNotEmpty(j_query_off)) {
            j_query_off = j_query_off.concat(offconditions);
          } else {
            j_query_off = offconditions;
          }
          this.params.params_jquery = j_query_off;
          this.params.status = '0';
          break;
        default:
          break;
      }
      this.shownTab = [this.activeName];
      this.$refs[`treeCmp_${this.activeName}`][0].loadTree('ROOT', () => {
        this.$refs[`treeCmp_${this.activeName}`][0].initValue();
      });
    },
  },
  mounted() {
    // 窗口改变 高度重新计算
    window.addEventListener('resize', () => {
      this.initHeight();
    });
    // 初始化过滤条件
    const sql = " and (NODETYPE = 'GENERAL' or (NODETYPE = 'LEAF' AND STATUS = '1' ))";
    this.params.params_whereSql = JE.isEmpty(this.params.whereSql) ? sql : this.params.whereSql + sql;
    let j_query = Ext.clone(this.params.j_query || []);
    const conditions = [
      {
        type: 'and',
        value: [
          { type: '=', code: 'NODETYPE', value: 'GENERAL' },
          {
            type: 'or',
            value: [
              { type: '=', code: 'STATUS', value: '1' },
              { type: '=', code: 'NODETYPE', value: 'LEAF' },
            ],
          },
        ],
      },
    ];
    if (JE.isNotEmpty(j_query)) {
      j_query = j_query.concat(conditions);
    } else {
      j_query = conditions;
    }
    this.params.params_jquery = j_query;
    this.params.status = '1';
    // this.params.enableFilter = true;
    // 初始化布局参数
    this.initDialogData();
    // 已选择回显
    this.echoValue();
  },
  methods: {
    // 每次打开初始化
    initDialogData() {
      this.isFullscreen = false; // 是否全屏
      this.allSelectList = [];// 所有tab选中的数据
      // 根据配置params.types 处理显示哪几个tab
      const tabs = [];
      if (this.params.types) {
        this.params.types.forEach((item) => {
          switch (item) {
            case 'common':
              tabs.push({ label: this.$t('common'), name: 'common' });
              break;
            case 'dept':
              tabs.push({ label: this.$t('dept'), name: 'dept' });
              break;
            case 'role':
              tabs.push({ label: this.$t('role'), name: 'role' });
              break;
            case 'post':
              tabs.push({ label: this.$t('post'), name: 'post' });
              break;
            case 'group':
              tabs.push({ label: this.$t('group'), name: 'group' });
              break;
            default:
              break;
          }
        });
        this.tabs = tabs;
      }
      this.activeName = this.tabs[0].name; // 默认选中哪个tab
      this.shownTab = [this.activeName];
      this.$nextTick(() => {
        // 如果不启用人员状态筛选
        if (!this.params.enableFilter) {
          $('#person-selector-dialog .el-dialog__footer').css({ 'text-align': 'right' });
        }
        // 处理展示层级
        $('#person-selector-dialog').css({ 'z-index': getMaxZindex() + 2 });
        this.initHeight();
        this.$refs[`treeCmp_${this.activeName}`][0].loadTree('ROOT', () => {
          this.$refs[`treeCmp_${this.activeName}`][0].initValue();
        });
      });
    },
    // 处理弹窗高度
    initHeight() {
      this.$nextTick(() => {
        const bodyheight = $('body').height();
        $('.selected-person .person-list').height(bodyheight - 384);
        $('.selected-person .person-table').height(bodyheight - 384);
        if (this.activeName == 'group') {
          $(`.person-dialog-tabs .btree-${this.activeName}`).height(bodyheight - 444);
        } else {
          $(`.person-dialog-tabs .btree-${this.activeName}`).height(bodyheight - 412);
        }
        if (Ext.isIE9m) {
          $('.pro-vue-person-selector .el-main').height(bodyheight - 312);
        }
      });
    },
    // 根据params.value回显值
    echoValue() {
      const { value, valueType } = this.params;
      // 如果值为空或者没有对应的主键字段，取消默认选中
      if (JE.isEmpty(value)) return;
      // 初始化配置
      const ddCode = 'JE_CORE_DEPTUSER';// 配置编码 不传默认查部门的
      // 查询选择的树形默认异步操作
      const ddList = [{
        ddCode,
        ddName: '',
        async: this.params.async,
        whereSql: this.params.params_whereSql || '',
        j_query: this.params.params_jquery || {},
        orderSql: '',
        parentSql: '',
        rootId: '',
        nodeInfo: ddCode,
        initParams: {},
        moreRoot: false,
        queryField: '',
        nodeField: '',
        formatValue: '',
      }];
      const that = this;
      // 查询节点
      JE.ajax({
        url: JE.getUrlMaps('je.core.dd.tree.findAsyncNodes'),
        params: {
          type: valueType || 'id', // 不传默认id
          value,
          strData: JE.encode(ddList),
        },
        success(data) {
          const res = JE.getAjaxData(data);
          // 处理下已选择的数据
          res.forEach((item) => {
            // 记录下系统配置的disabled值  0 可选有效数据  1 不可选无效数据
            item.disable = item.disabled;
            // 默认全部能选
            item.disabled = false;
            item.id_ = item.id;
            // id处理 取截取的数组的第一项 为ID
            const [key] = item.id.split('_');
            item.id = key;
          });
          that.allSelectList = res;
        },
      });
    },
    // 接收选中的数据
    doSelected(data, length, isSel) {
      this.treeDataLength = length;
      this.allSelectList = data;
      if (isSel) {
        this.doSure();
      }
    },
    // 新建组
    createGroup() {
      if (this.treeDataLength > 49) {
        return JE.msg(this.$t('groupLimit'));
      }
      this.groupMemberIds = [];
      this.newChildren = [];
      const that = this;
      JE.selectWin({
        title: that.$t('personnel'),
        type: 'tree',
        configInfo: 'JE_CORE_DEPTUSER,,,M',
        whereSql: ' AND STATUS=\'1\' AND VALID=\'1\'',
        j_query: Ext.encode({
          custom: [
            { code: 'STATUS', type: '=', value: '1' },
            { code: 'VALID', type: '=', value: '1' },
          ],
        }),
        callback(res) {
          if (res.length > 100) {
            return JE.alert(that.$t('personLimit'));
          }
          res.forEach((item) => {
            that.groupMemberIds.push(item.data.id);
          });
          that.inputGroupName();
        },
      });
    },
    // 工作组新建 输入名称
    inputGroupName(ids) {
      // 如果有ids 则是修改  没有就是新建
      if (ids) {
        this.groupMemberIds = ids;
      }
      this.$prompt(this.$t('inputName'), this.$t('prompt'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        closeOnClickModal: false,
        closeOnPressEscape: false,
        inputValidator: this.groupNameValid, // 工作组名称校验
      }).then(({ value }) => {
        setCommonGroup({
          type: 'group',
          ids: this.groupMemberIds.join(','),
          groupName: value,
        }).then((data) => {
          if (!data.success) {
            return JE.msg(this.$t('createFailure'));
          }
          JE.msg(this.$t('createSuccess'));
          // 新建工作组后要刷新工作组列表
          if (this.activeName === 'group') {
            this.$refs[`treeCmp_${this.activeName}`][0].loadTree('ROOT', () => {
              this.$refs[`treeCmp_${this.activeName}`][0].initValue();
            });
          }
        });
      }).catch(() => {
        // console.log('取消');
      });
    },
    // 校验工作组名称输入
    groupNameValid(value) {
      // 不能为空
      if (value == null || !value.trim()) {
        return this.$t('inputEmptyMsg');
      }
      // 最多十个字符
      if (value.trim().length > 10) {
        return this.$t('inputErrorMsg');
      }
    },
    // 清空
    clearAll() {
      this.allSelectList = [];
      this.isClear = true;
      // 定时再置为false 以便再次清空
      setTimeout(() => {
        this.isClear = false;
      });
    },
    // 删除一个人
    removePerson(em, index) {
      this.allSelectList.splice(index, 1);
      const trees = this.$refs || {};
      Object.keys(trees).forEach((key) => {
        if (this.$refs[key][0]) {
          if (this.params.selectType == 'single') {
            this.$refs[key][0].$refs.tree.setCurrentKey(null);
          } else {
            this.$refs[key][0].$refs.tree.setChecked(em, false);
          }
        }
      });
    },
    // 全屏
    fullClick() {
      this.isFullscreen = !this.isFullscreen;
      this.initFullHeight();
    },
    // 处理全屏的高度
    initFullHeight() {
      if (this.isFullscreen) {
        const bodyheight = $('body').height();
        $('.selected-person .person-list').height(bodyheight - 199);
        $('.selected-person .person-table').height(bodyheight - 199);
        if (this.activeName == 'group') {
          $(`.person-dialog-tabs .btree-${this.activeName}`).height(bodyheight - 259);
        } else {
          $(`.person-dialog-tabs .btree-${this.activeName}`).height(bodyheight - 227);
        }
        if (Ext.isIE9m) {
          $('.pro-vue-person-selector .el-main').height(bodyheight - 127);
        }
      } else {
        this.initHeight();
      }
    },
    // 切换tabs
    handleClick(tab) {
      if (this.shownTab.includes(tab.name)) {
        this.needReload = false;
      } else {
        this.needReload = true;
        this.shownTab.push(tab.name);
      }
      // 每次切换tab 则初始化回显当前tree的默认选中值
      this.$nextTick(() => {
        // 如果是工作组 则调用loadTree再初始化
        if (tab.name === 'group' || this.needReload) {
          this.$refs[`treeCmp_${tab.name}`][0].loadTree('ROOT', () => {
            this.$refs[`treeCmp_${tab.name}`][0].initValue();
          });
        } else {
          this.$refs[`treeCmp_${tab.name}`][0].initValue();
        }
        // 处理高度
        this.initFullHeight();
      });
    },
    // 常用无数据 切换到部门
    toggle2dept() {
      this.activeName = 'dept';
      this.shownTab = [this.activeName];
      this.$nextTick(() => {
        this.$refs[`treeCmp_${this.activeName}`][0].loadTree('ROOT', () => {
          this.$refs[`treeCmp_${this.activeName}`][0].initValue();
        });
      });
      // 处理高度
      this.initFullHeight();
    },
    // 确定
    doSure() {
      const ids = [];
      this.allSelectList.forEach((item) => {
        ids.push(item.id);
      });
      const param = {
        type: 'common',
        ids: ids.join(','),
      };
      // 确定时获得用户数据，绑定业务bean
      const users = JE.ajax({
        url: '/je/load',
        params: {
          tableCode: 'JE_CORE_ENDUSER',
          limit: -1,
          whereSql: ` AND USERID IN ('${ids.join("','")}')`,
          j_query: Ext.encode({
            custom: [
              { code: 'USERID', type: 'in', value: ids },
            ],
          }),
        },
      }).rows;
      this.allSelectList.forEach((item) => {
        users.forEach((user) => {
          if (user.USERID == item.id) {
            item.bean = user;
          }
        });
      });
      // 设为常用人员
      setCommonGroup(param);

      this.params.show = false;
      return this.params.callback && this.params.callback(this.allSelectList);
    },
  },
};
</script>
<style lang="scss">
.pro-vue-person-selector {
  .el-dialog__header {
    border-bottom: 1px solid #e4e4e4;
    font-weight: 700;
    color: #333;
  }
  .el-dialog__headerbtn {
    font-size: 20px;
  }
  .el-dialog__body {
    padding: 5px 0;
    .el-container {
      overflow: hidden;
    }
    .el-aside {
      border-right: 1px solid #e4e4e4;
      float: left;
      .el-tabs--border-card {
        border: 0;
        box-shadow: none;
        &>.el-tabs__header {
          border: 0;
          .el-tabs__item {
            border: 0;
          }
        }
      }
      .tab-group-cont {
        box-shadow: none;
      }
      .add-btn {
        margin-left: 15px;
        color: #2f6bcf;
        &:hover {
          color: #6696e9;
        }
      }
    }
    .el-main {
      padding: 0 20px;
    }
  }
  .createMask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    opacity: .5;
    background: #000;
    z-index: -1
  }
  .fullScreen-icon {
    position: absolute;
    top: 23px;
    right: 50px;
    font-weight: 400;
    font-size: 14px;
    cursor: pointer;
    color: #ADADAD;
    &:hover {
      color: #2f6bcf;
    }
  }
  .el-dialog__footer {
    padding: 15px 20px;
    padding-left: 10px;
    background-color: #f4f6f9;
    text-align: left;
    .el-radio--small.is-bordered {
      border: 0;
      margin-right: 0;
      padding-right: 8px;
    }
    .el-radio--small.is-bordered .el-radio__label {
      font-size: 14px;
    }
    .el-button--small {
      padding: 8px 25px;
    }
    .el-button--primary {
      background-color: #2f6bcf;
      border-color: #2f6bcf;
      &:hover {
        background-color: #6696e9;
        border-color: #6696e9;
      }
    }
  }
}
.el-message-box__wrapper {
  z-index: 10000000 !important;
  .el-button--small {
    padding: 8px 25px;
  }
  .el-button--primary {
    background-color: #2f6bcf;
    border-color: #2f6bcf;
    &:hover {
      background-color: #6696e9;
      border-color: #6696e9;
    }
  }
}
</style>
